<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #one,#two {
        width: 200px;
        height: 200px;
        position: absolute;
        background: red;
    }

    #two  {
        z-index: -1;
    }
    img {
        width: 200px;
        height: 200px;
    }
</style>

<body>
    <div id='one'>
        <img src="1.jpg" alt="">
    </div>
    <div id = 'two'>
        <img src="2.jpg" alt="">
    </div>
</body>
<script type="text/javascript">

    function Dxy(id) {
        this.one = document.getElementById(id)
        this.disx = 0;
        this.disy = 0;
    }

    Dxy.prototype.init = function () {
        var This = this
        this.one.onmousedown = function (ev) {
            This.down(ev)
            return false
        }
    }




    Dxy.prototype.down = function (ev) {
        var This = this;
        var event = ev || window.event
        this.disx = event.clientX - this.one.offsetLeft
        this.disy = event.clientY - this.one.offsetTop
        document.onmousemove = function (ev) {
            This.move(ev)
        }
        document.onmouseup = function () {
            This.up()
        }
    }


    Dxy.prototype.move = function (ev) {
        var event = ev || window.event;
        this.one.style.left = event.clientX - this.disx + 'px';
        this.one.style.top = event.clientY - this.disy + 'px';
    }



    Dxy.prototype.up = function () {
        document.onmousemove = null;
        document.onmouseup = null
    }

    function limitDrag(id){
        Dxy.call(this,id)
    }


    for (var i in Dxy.prototype){
        limitDrag.prototype[i] = Dxy.prototype[i]
    }

    
    limitDrag.prototype.move = function(ev){
        var event =ev || window.event;
        var left = event.clientX - this.disx;
        var top = event.clientY - this.disy;
        if (left < 0) left = 0;
        if (left > document.documentElement.clientWidth - this.one.offsetWidth) left = document.documentElement.clientWidth - this.one.offsetWidth;
        if (top < 0) top = 0;
        if (top > document.documentElement.clientHeight - this.one.offsetHeight) top = document.documentElement.clientHeight - this.one.offsetHeight;
        this.one.style.left = left+'px'
        this.one.style.top = top +'px'
    }
    var dxy = new Dxy('one');
    dxy.init();
    var tw = new limitDrag('two')
    tw.init()
</script>

</html>